﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Data.Linq;
using System.Linq;
using System.Text.RegularExpressions;
using System.Windows;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using BackgroundAudioPlayback;
using Microsoft.Phone;
using Microsoft.Phone.Controls;
using Microsoft.Xna.Framework.Media;
using SQLite;
using WOIM_NET.Music;
using Microsoft.Phone.BackgroundAudio;

namespace WOIM_NET
{
    public partial class PlayPage : PhoneApplicationPage
    {
        public static AlbumModel AlbumPlay = new AlbumModel();
        public static BitmapImage AvatarImage = null;
        public static AlbumsViewModel RelatedAlbums = new AlbumsViewModel();
        public static string ModelPlaying;

        public PlayPage()
        {
            InitializeComponent();
            //AlbumPlay = new AlbumModel();
            NowPlayingPage.DataContext = AlbumPlay;
            //RelatedAlbums = new AlbumsViewModel();
            RelatedAlbumsList.DataContext = RelatedAlbums;

            BackgroundAudioPlayer.Instance.PlayStateChanged += new EventHandler(Instance_PlayStateChanged);
        }

        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            string txt, songName, songArtist, songAlbum, songUrl, songAvatar, songAlbumUrl;
            if (NavigationContext.QueryString.TryGetValue("model", out ModelPlaying))
            {
                if (ModelPlaying == "NowPlaying")
                {
                    using (var db = new SQLiteConnection(App.dbPath))
                    {
                        List<PlayingList> NowList = db.Table<PlayingList>().ToList();
                        System.Windows.Deployment.Current.Dispatcher.BeginInvoke(() =>
                        {
                            AlbumPlay.Name = NowList[0].Album;
                            AlbumPlay.Avatar = NowList[0].Avatar;
                            AlbumPlay.Artist = NowList[0].Artist;
                            AlbumPlay.Url = NowList[0].LinkToAlbum;
                            AlbumPlay.ListSongs.Clear();
                            foreach (PlayingList song in NowList)
                            {
                                AlbumPlay.ListSongs.Add(new SongModel() { Artist = song.Artist, Name = song.Title, Url = song.Url, Avatar = song.Avatar });
                            }
                        });
                    }
                }
                else if (ModelPlaying == "song")
                {
                    //Change UI Player
                    if (NavigationContext.QueryString.TryGetValue("name", out songName))
                    {
                        CurrentSongTxt.Text = songName;
                    }
                    if (NavigationContext.QueryString.TryGetValue("avatar", out songAvatar))
                    {
                        AlbumPlay.Avatar = songAvatar;
                    }
                    if (NavigationContext.QueryString.TryGetValue("artist", out songArtist))
                    {
                        AlbumPlay.Url = songArtist;
                    }
                    if (NavigationContext.QueryString.TryGetValue("album", out songAlbum))
                    {
                        AlbumPlay.Name = songAlbum;
                    }
                    if (NavigationContext.QueryString.TryGetValue("linkAlbum", out songAlbumUrl))
                    {
                        AlbumPlay.Url = songAlbumUrl;
                    }
                    if (NavigationContext.QueryString.TryGetValue("url", out songUrl))
                    {
                    }
                    //Add to List Player
                    AlbumPlay.ListSongs.Clear();
                    AlbumPlay.ListSongs.Add(new SongModel() { Name = songName });
                    //Add to Background Player
                    using (var db = new SQLiteConnection(App.dbPath))
                    {
                        db.RunInTransaction(() =>
                        {
                            db.DeleteAll<PlayingList>();
                            db.Insert(new PlayingList() { Title = songName, Url = songUrl, Artist = songArtist, Album = songAlbum, Avatar = songAvatar, LinkToAlbum = songAlbumUrl});
                        });
                    }
                    BackgroundAudioPlayer.Instance.Play(); 
                }
                else if (ModelPlaying == "AlbumPlay")
                {
                    //Get song for album playings online
                    if (NavigationContext.QueryString.TryGetValue("name", out txt))
                    {
                        AlbumPlay.Name = txt;
                    }

                    if (NavigationContext.QueryString.TryGetValue("avatar", out txt))
                    {
                        //AvatarImage = new BitmapImage(new Uri(txt, UriKind.Absolute));
                        //AvatarAlbum.Source = AvatarImage;
                        AlbumPlay.Avatar = txt;
                    }

                    string urlSong;
                    if (NavigationContext.QueryString.TryGetValue("url", out urlSong))
                    {
                        if (AlbumPlay.Url != urlSong)
                        {
                            AlbumPlay.Url = urlSong;
                            AlbumPlay.GetSongTracks();
                        }
                    }
                }
            }
            NavigationContext.QueryString.Clear();

            //Set player control
            if (PlayState.Playing == BackgroundAudioPlayer.Instance.PlayerState)
            {
                playButton.Content = "Pause";
                CurrentSongTxt.Text = BackgroundAudioPlayer.Instance.Track.Title;ArtistTextBlock.Text = BackgroundAudioPlayer.Instance.Track.Artist;
                ArtistTextBlock.Text = BackgroundAudioPlayer.Instance.Track.Artist;

            }
            else
            {
                playButton.Content = "Play";
                CurrentSongTxt.Text = "";
            }

        }

        private void playButton_Click(object sender, System.Windows.RoutedEventArgs e)
        {
            if (PlayState.Playing == BackgroundAudioPlayer.Instance.PlayerState)
            {
                BackgroundAudioPlayer.Instance.Pause();
            }
            else
            {
                BackgroundAudioPlayer.Instance.Play();
            }
        }

        private void nextButton_Click(object sender, System.Windows.RoutedEventArgs e)
        {
            BackgroundAudioPlayer.Instance.SkipNext();
        }

        private void backButton_Click(object sender, System.Windows.RoutedEventArgs e)
        {
            BackgroundAudioPlayer.Instance.SkipPrevious();
        }


        private void Instance_PlayStateChanged(object sender, EventArgs e)
        {
            switch (BackgroundAudioPlayer.Instance.PlayerState)
            {
                case PlayState.Playing:
                    playButton.Content = "pause";
                    break;

                case PlayState.Paused:
                case PlayState.Stopped:
                    playButton.Content = "play";
                    break;
            }

            if (null != BackgroundAudioPlayer.Instance.Track)
            {
                CurrentSongTxt.Text = BackgroundAudioPlayer.Instance.Track.Title;
                ArtistTextBlock.Text = BackgroundAudioPlayer.Instance.Track.Artist;
            }
        }

        private void Pivot_SelectionChanged(object sender, System.Windows.Controls.SelectionChangedEventArgs e)
        {
            if (PivotPages.SelectedIndex == 1)
            {
                if (RelatedAlbums.AlbumUrl != AlbumPlay.Url)
                {
                    RelatedAlbums.LoadData(AlbumPlay.Url);
                }
            }
        }

        private void RelatedAlbumsList_Tap(object sender, System.Windows.Input.GestureEventArgs e)
        {
            AlbumModel album = ((AlbumModel) RelatedAlbumsList.SelectedItem);
            
            NameTextBlock.Text = album.Name;
            AvatarImage = new BitmapImage(new Uri(album.Avatar, UriKind.Absolute));
            AvatarAlbum.Source = AvatarImage;

            if (AlbumPlay.Url != album.Url)
            {
                AlbumPlay.Url = album.Url;
                AlbumPlay.GetSongTracks();
            }

            //Set player control
            if (PlayState.Playing == BackgroundAudioPlayer.Instance.PlayerState)
            {
                playButton.Content = "Pause";
                CurrentSongTxt.Text = BackgroundAudioPlayer.Instance.Track.Title; 
                ArtistTextBlock.Text = BackgroundAudioPlayer.Instance.Track.Artist;
            }
            else
            {
                playButton.Content = "Play";
                CurrentSongTxt.Text = "";
            }

            PivotPages.SelectedIndex = 0;
        }

        private void btFavorite_Tap(object sender, System.Windows.Input.GestureEventArgs e)
        {
            using (var db = new SQLiteConnection(App.dbPath))
            {
                db.RunInTransaction(() =>
                {
                    //db.DeleteAll<PlayingList>();
                    AudioTrack track = BackgroundAudioPlayer.Instance.Track;
                    db.Insert(new FavoriteList() { Title = track.Title, Url = track.Source.ToString(), Artist = track.Artist, Album = track.Album, Avatar = AlbumPlay.Avatar, LinkToAlbum = AlbumPlay.Url });
                    MessageBox.Show("Add track " + track.Title + " to favorite' list success!");
                    App.FavoriteViewModel.LoadData();
                });
            }
        }

    }
}